import { createStore } from "vuex";
import { getAdminInfo as getAdminData } from "../request/http";

interface MenuObj {
  parentId: number;
  id: number;
  name: string;
  children?: MenuObj[];
}

interface State {
  menus: MenuObj[];
}

interface NewMenu {
  [key: string]: MenuObj;
}

const store = createStore<State>({
  state() {
    return {
      menus: [],
    };
  },

  getters: {
    genNewMenus(state) {
      // 获取state里面的权限列表，一级菜单
      const menus = state.menus;
      const newMenus: NewMenu = {};
      for (let i = 0; i < menus.length; i++) {
        // 一级菜单
        if (menus[i].parentId === 0) {
          newMenus[menus[i].id] = { ...menus[i], ...newMenus[menus[i].id] };
        } else {
          // 二级菜单
          const subMenu = menus[i];
          // 二级菜单所对应的一级菜单对象
          newMenus[subMenu.parentId] = newMenus[subMenu.parentId] || {};
          newMenus[subMenu.parentId].children =
            newMenus[subMenu.parentId].children || [];
          // 添加二级菜单到对应的一级菜单对象上的children
          newMenus[subMenu.parentId].children!.push(subMenu);
        }
      }
      return newMenus;
    },

    permissionMenus(state) {
      return state.menus.map((item) => item.name);
    },
  },

  mutations: {
    updateMenus(state, menus) {
      state.menus = menus;
    },
  },

  actions: {
    getAdminInfo({ state, commit }) {
      return getAdminData().then((res) => {
        if (res.code === 200) {
          commit("updateMenus", res.data.menus);
          return res.data;
        } else {
          return Promise.reject(res);
        }
      });
    },
  },
});

export default store;
